import { Injectable, Inject, BadRequestException, UnprocessableEntityException } from '@nestjs/common'
import { CreateUserDto } from './dto/create-user.dto'
import { UpdateUserDto } from './dto/update-user.dto'
import { User } from './entities/user.entity'
import { Repository } from 'typeorm'


@Injectable()
export class UserService {

  constructor(
    @Inject('USER_REPOSITORY')
    private readonly userRepository: Repository<User>
  ) { }

  // 创建用户
  async create(createUserDto: CreateUserDto): Promise<User> | undefined {
    let res = undefined
    try {
      res = await this.userRepository.insert(createUserDto)
    } catch (error) {
      throw new BadRequestException(error)
    }

    return res
  }

  // 查询所有用户
  async findAll(): Promise<[User[], number]> | undefined {
    let res = undefined
    try {
      res = await this.userRepository.findAndCount()
      res[0] = res[0].map(user => {
        delete user.password
        return user
      });
    } catch (error) {
      throw new UnprocessableEntityException('查询用户出错')
    }
    return res
  }

  // 根据id或者username查找用户
  async findOne(condition: number | string): Promise<User> | undefined {
    console.log(111);
    
    console.log(typeof condition, condition);
    
    let res = undefined
    try {
      let result = undefined;
      if (typeof condition == 'string')
        result = await this.userRepository.findOne({ username: condition })
      else
        result = await this.userRepository.findOne({ uid: condition })
      
        // delete result.password;
        res = result

    } catch (error) {
      throw new UnprocessableEntityException('查询用户出错')
    }
    return res
  }


  // 更新id为指定id的用户的信息
  async update(id: number, updateUserDto: UpdateUserDto) {
    let res = undefined
    try {
      res = await this.userRepository.update({ uid: id }, updateUserDto)
    } catch (error) {
      throw new UnprocessableEntityException('更新用户出错')
    }
    return res
  }

  // 删除id为 指定id 的用户
  async remove(id: number) {
    let res = undefined
    try {
      res = await this.userRepository.delete({ uid: id })
    } catch (error) {
      throw new UnprocessableEntityException('删除用户出错')
    }
    return res
  }
}
